<template>
  <div class="chat-container">
    <!-- 菜单栏 -->
    <div class="menu-bar">
      <div class="menu-left">
        <div class="project-select">
          <label for="project-selector">Select Project</label>
          <select v-model="selectedProjectToken" id="project-selector" class="project-dropdown" @change="handleProjectChange">
            <option v-for="project in projects" :key="project.value" :value="project.value">
              {{ project.label }}
            </option>
          </select>
          <button @click="handleProjectChange" class="link-button">Link</button>
        </div>
      </div>
      <div class="menu-right">
        <div class="route-select">
          <label for="route-selector">Message Route</label>
          <select v-model="selectedRoute" id="route-selector" class="route-dropdown" @change="handleRouteChange">
            <option v-for="route in availableRoutes" :key="route.value" :value="route.value">
              {{ route.label }}
            </option>
          </select>
        </div>
        <div class="route-select">
          <label for="audio-route-selector">Audio Route</label>
          <select v-model="selectedAudioRoute" id="audio-route-selector" class="route-dropdown" @change="handleAudioRouteChange">
            <option v-for="route in availableAudioRoutes" :key="route.value" :value="route.value">
              {{ route.label }}
            </option>
          </select>
        </div>
      </div>
    </div>

    <!-- 对话记录区域 -->
    <div class="messages">
      <div v-for="message in messages" :key="message.id" class="message">
        <div v-if="message.type === 'text'" class="message-text">
          <NormalMessage
            :content="message.content"
            :sender="message.sender"
            :timestamp="message.timestamp"
          />
        </div>
        
        <FunctionTest 
          v-else-if="message.type === 'functionTest'"
          :input="message.content"
          @response="handleFunctionResponse"
          class="function-test-message"
        />
      </div>
    </div>

    <!-- 输入框区域 -->
    <div class="input-container">
      <textarea
        v-model="message"
        class="message-input"
        placeholder="Type your message..."
        :style="{ height: inputHeight + 'px' }"
        @input="adjustInputHeight"
      ></textarea>
      <button @click="sendMessageHandler" class="send-button">Send</button>
    </div>

    <div class="audio-controls" v-if="selectedAudioRoute">
      <button 
        @click="isRecording ? stopRecording() : startAudioRecording()"
        :class="{ 'recording': isRecording }"
      >
        {{ isRecording ? 'Stop Recording' : 'Start Recording' }}
      </button>
      <span v-if="isRecording" class="recording-indicator">● Recording...</span>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'ChatView'
}
</script>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import {useServer} from '@/components/ts/useServer';
import {useUserStore} from '@/stores/userStore';
import FunctionTest from '@/components/chatComponents/FunctionTest.vue'
import NormalMessage from '@/components/chatComponents/NormalMessage.vue'

const message = ref('');
const inputHeight = ref(40);
const projects = ref<{ value: string; label: string }[]>([]);
const selectedProjectToken = ref<string>('');
const selectedRoute = ref<string>('');
const selectedAudioRoute = ref<string>('');
const availableRoutes = ref<{ value: string; label: string }[]>([]);
const availableAudioRoutes = ref<{ value: string; label: string }[]>([]);
const state = useUserStore()

const { 
  post, 
  ws, 
  connectWebSocket, 
  sendMessage, 
  closeWebSocket, 
  messages, 
  isConnected, 
  currentProjectToken, 
  sendDataInRoute,
  selectMessageRoute,
  selectAudioRoute,
  startAudioRecording,
  stopAudioRecording,
  isRecording
} = useServer();

// 使用后端接口获取 project 列表
const getProjects = async () => {
  try {
    const response = await post('getUserRunningProjects', { userID: state.currentUser });
    projects.value = response.data.map((project: any) => ({
      value: project.full_url,
      label: `${project.username}_${project.project_name}`
    }));
  } catch (error) {
    console.error('Failed to fetch projects:', error);
  }
};

// 获取可用路由
const getAvailableRoutes = async () => {
  try {
    const response = await post('getAvailableRoutes', { project_token: selectedProjectToken.value });
    console.log(response)
    availableRoutes.value = response.data.messageRoutes.map((route: any) => ({
      value: route.value,
      label: route.node_name
    }));
    availableAudioRoutes.value = response.data.audioRoutes.map((route: any) => ({
      value: route.value,
      label: route.node_name
    }));
  } catch (error) {
    console.error('Failed to fetch routes:', error);
  }
};

// 监听 project 变化，切换 WebSocket 连接
const handleProjectChange = async () => {
  console.log('Selected project changed:', selectedProjectToken.value)
  
  // 关闭当前项目的连接
  if (currentProjectToken.value) {
    closeWebSocket(currentProjectToken.value);
  }

  if (selectedProjectToken.value) {
    connectWebSocket(selectedProjectToken.value);
    // 获取新的可用路由
    await getAvailableRoutes();
  }
};

// 处理消息路由变化
const handleRouteChange = () => {
  console.log('Selected message route changed:', selectedRoute.value);
  // 这里可以添加路由切换的相关逻辑
  if(selectedRoute.value){
    selectMessageRoute(selectedRoute.value);
  }
};

// 处理音频路由变化
const handleAudioRouteChange = () => {
  console.log('Selected audio route changed:', selectedAudioRoute.value);
  if(selectedAudioRoute.value){
    selectAudioRoute(selectedAudioRoute.value);
  }
};

// 停止音频录制
const stopRecording = () => {
  stopAudioRecording();
};

// 发送消息
const sendMessageHandler = () => {
  if (message.value.trim() === '') return;
  
  // Add user message to messages array
  messages.value.push({
    id: Date.now().toString(),
    content: message.value,
    sender: 'user',
    type: 'text',
    timestamp: Date.now()
  });
  
  sendMessage(message.value);
  message.value = '';
};

const handleFunctionResponse = (response: any) => {
  console.log('Function response:', response)
  
  const messageToSend = {
    type: 'function_response',
    route: response.route,
    correlation_id: response.correlation_id,
    status: response.status,
    data: response.result
  }

  const currentWs = ws();
  if (currentWs && currentWs.connected) {
    sendDataInRoute(response.route, messageToSend);
  } else {
    console.error('WebSocket is not connected')
  }
}

// 在组件挂载后获取 project
onMounted(() => {
  getProjects();
});

onUnmounted(() => {
  stopRecording();
  if (currentProjectToken.value) {
    closeWebSocket(currentProjectToken.value);
  }
});

// 调整输入框高度
const adjustInputHeight = () => {
  const textarea = document.querySelector('.message-input') as HTMLTextAreaElement;
  if (textarea) {
    inputHeight.value = textarea.scrollHeight > 40 ? textarea.scrollHeight : 40;
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 20px;
  background-color: #f5f5f5;
  gap: 20px;
}

.menu-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.menu-left, .menu-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.project-select, .route-select {
  display: flex;
  align-items: center;
  gap: 10px;
}

.project-select label, .route-select label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  white-space: nowrap;
}

.project-dropdown, .route-dropdown {
  padding: 8px 12px;
  border-radius: 8px;
  border: 1px solid #ddd;
  font-size: 14px;
  min-width: 180px;
  background-color: #fff;
  cursor: pointer;
}

.link-button {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.link-button:hover {
  background-color: #0056b3;
}

.messages {
  flex-grow: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message {
  margin-bottom: 15px;
}

.message-text {
  width: 100%;
}

.function-test-message {
  margin-top: 10px;
}

.input-container {
  display: flex;
  gap: 15px;
  padding: 15px;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-input {
  flex-grow: 1;
  min-height: 40px;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: none;
  font-size: 14px;
  line-height: 1.5;
}

.message-input:focus {
  outline: none;
  border-color: #007bff;
}

.send-button {
  padding: 12px 24px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.send-button:hover {
  background-color: #0056b3;
  transform: translateY(-1px);
}

.send-button:active {
  transform: translateY(0);
}

.audio-controls {
  margin: 10px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.recording {
  background-color: #ff4444;
  color: white;
}

.recording-indicator {
  color: #ff4444;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}
</style>
